package com.madvirus.review;

import java.util.List;

import com.madvirus.review.data.Review;
import com.madvirus.review.data.ReviewFetcher;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

public class ReviewList extends ListActivity {

	private static final int NUM_RESULTS_PER_PAGE = 10;

	private TextView empty;
	private ProgressDialog progressDialog;
	private ReviewAdapter reviewAdapter;
	private List<Review> reviews;

	private final Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			if (reviews == null || reviews.size() == 0) {
				empty.setText("No Data");
			} else {
				reviewAdapter = new ReviewAdapter(ReviewList.this, reviews);
				setListAdapter(reviewAdapter);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.review_list);

		empty = (TextView) findViewById(R.id.empty);
		ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView.setEmptyView(empty);
	}

	@Override
	protected void onResume() {
		super.onResume();
		RestaurantFinderApplication application = (RestaurantFinderApplication) getApplication();
		loadReviews(application.getReviewCriteriaLocation(),
				application.getReviewCriteriaCuisine(), 1);
	}

	private void loadReviews(String location, String cuisine, int startFrom) {
		final ReviewFetcher rf = new ReviewFetcher(location, cuisine, "ALL",
				startFrom, NUM_RESULTS_PER_PAGE);
		progressDialog = ProgressDialog.show(this, "Working...",
				"Retrieving reviews", true, false);

		new Thread() {
			public void run() {
				reviews = rf.getReviews();
				handler.sendEmptyMessage(0);
			}
		}.start();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		RestaurantFinderApplication application = (RestaurantFinderApplication) getApplication();
		application.setCurrentReview(reviews.get(position));

		Intent intent = new Intent(this, ReviewDetail.class);
		startActivity(intent);
	}

}
